#coding=utf-8
import datetime
from decimal import Decimal
from BeautifulSoup import BeautifulSoup
from utility import get_soup2, get_jd, get_yjs

class Price(object):
    '''每个交易日的价格'''
    def __init__(self, code=None):
        self.code = code
        
        self.date = '1970-01-01'
        
        self.open = 0.0
        self.close = 0.0
        self.highest = 0.0
        self.lowest = 0.0
        
        self.volume = 0
        self.amount = 0
        
        #复权因子
        self.fuquan_ratio = 0
        
url_stock = 'http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s.phtml?year=%s&jidu=%s'
url_sindex = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s/type/S.phtml?year=%s&jidu=%s'

index_codes = {'szzs': '000001', 'szcz': '399001'}

def get_prices_from_soup(soup):

    def get_s(item):
        while True:
            r = item.string
            if r: return r.strip()
            item = item.contents[0]
            
    def get_price_from_row(row):
        
        r = []
        tds = row.findAll('td')

        for td in tds:
            r.append(get_s(td))

        if not r[0]:
            td0 = tds[0]
            rq = td0.contents[0].contents[1].string.strip()
            r[0] = rq
            
        for i in range(len(r)):
            r[i] = r[i].encode('u8')
        
        p = Price()
        
        p.date = r[0]
        
        p.open = float(r[1])
        p.highest = float(r[2])
        p.close = float(r[3])
        p.lowest = float(r[4])
        
        p.volume = int( Decimal(r[5]) * 100 )
        p.amount = int( Decimal(r[6]) * 10000 )   

        return p

    ps = []
    
    t = unicode('日期', 'u8')
    rq = soup.find(text = t)
    #如果在该季度内没有交易
    if not rq:return None 
    
    table = rq.parent.parent.parent.parent.parent
    trs = table.findAll('tr')[2:]

    for tr in trs:
        p = get_price_from_row(tr)
        ps.append(p)

    ps.reverse()
    
    return ps
               
def get_prices_by_jd(code, year, jd, fins='stock'):
    
    if fins == 'stock':
        
        u1 = url_stock%(code, year, jd)
        s = get_soup2(u1)
        ps = get_prices_from_soup(s)
        if not ps:return None
          
    elif fins == 'sindex':
        u3 = url_sindex%(code, year, jd)
        s = get_soup2(u3)
        ps = get_prices_from_soup(s)
        
        if not ps:return None
         
    for p in ps:
        p.code = code
        
    return ps
           
def get_price_on(code, tdate, fins='stock'):
    '''取得 某一 (股票 or 指数) 某一天(eg: "2009-07-07")的价格'''
    
    year, month, day = map(int, tdate.split('-'))
    jd = get_jd(month)
    ps = get_prices_by_jd(code, year, jd, fins)
    
    if not ps:
        return None
        
    for p in ps:
        if p.date == tdate:
            return p
    
    return None

def get_prices_between(code, start, end=datetime.date.today().isoformat(), fins='stock'):
    
    pss = []
    
    sy, sm, sd = map(int, start.split('-'))
    ey, em, ed = map(int, end.split('-'))
    
    yjs = get_yjs(sy, get_jd(sm), ey, get_jd(em) )  
    
    for yj in yjs:
        y,j = yj
        ps = get_prices_by_jd(code, y, j, fins)          
        if ps:pss.extend(ps)

    s = 0; e = 0
    for p in pss:
        if p.date >= start:
            s = pss.index(p)
            break
          
    for p in pss:        
        if p.date == end:
            e = pss.index(p) + 1
            break
            
        if p.date > end:
            e = pss.index(p)
            break
            
    if e == 0:return pss[s:]        
    return pss[s:e]

if __name__ == "__main__":
    #ps = get_prices_between('600036', start='2008-01-01', end='2009-06-01')
    ps = get_prices_between('399001', start='2008-01-01', end='2009-06-01', fins='sindex') 
        
    for p in ps:
        print p.date, p.close
    
    
    

